Code Listing 4. Primary Key Class UserPK

package org.article.util;

import java.sql.*;
import java.util.*;
import org.article.entitybean.*;
import javax.ejb.*;
import java.rmi.*;





public class UserPK   implements UniversumPK {

	 // for the sake of simplicity names match to those set in your database
	 // if desired a name map may be introduced for custom names
	 // for the same sake we omit some data validation issues
	 // exception are thrown with no messages, custom exceptions should be introduced
	
   
   private String [] columns = {"ID", "FIRST_NAME", "LAST_NAME", 
   	"ZIP_CODE", "PHONE"};
   	
   private String [] pkColumns = {"ID"};
   
   private HashMap pkValues = new HashMap();
    	
   private String tableName = "APP_USER";
   	 
   public String selectQuery, insertQuery, updateQuery, deleteQuery, findByWhereQuery;


	 private void init(){       // initialize SQL statements
	 	String where = " WHERE "; 
	 	findByWhereQuery = "SELECT ";
	 	selectQuery = "SELECT "; 
	 	insertQuery = "INSERT INTO " + tableName + " ( "; 
	 	updateQuery = "UPDATE " + tableName + " SET ";
	 	
	 	for (int i = 0; i < pkColumns.length; i++){
	 		where = where + (i==0?"":" AND ") + pkColumns[i] + " = ?";
	 		findByWhereQuery = findByWhereQuery + (i==0?"":",") + pkColumns[i];
	 	}
	 		
	  String qst = "?";	  
	  for (int i = 0; i < columns.length; i++){
	 		selectQuery = selectQuery + (i==0?"":",") + columns[i];	
	 		insertQuery = insertQuery + (i==0?"":",") + columns[i];	
			updateQuery = updateQuery + (i==0?"":",") + columns[i] + " = ?";
	 		qst = qst + (i==0?"":",?");
	 	}
	 	
	 	selectQuery = selectQuery + " FROM " + tableName + where;
	 	insertQuery = insertQuery + " ) VALUES ( " + qst + " )";
	 	updateQuery = updateQuery + where;
	 	deleteQuery = "DELETE FROM " + tableName + where;
	  findByWhereQuery =  findByWhereQuery + " FROM " + tableName + " WHERE ";
	 }
	 
	 // EJB specs reqired
	 public int hashCode(){   
			Object ob = pkValues.get("ID");
      	return ((Integer)ob).intValue();    
   }
	 
   // EJB specs required
   public String toString()   {
   	String rtr = "\n";
   	for (int i = 0; i < pkColumns.length; i++)
   		rtr = rtr + (i==0?"":", ") + pkColumns[i] + " = " + pkValues.get(pkColumns[i]);

    return rtr;   
   }
   
   // EJB specs required
   public boolean equals(Object obj) {	
   	if (obj == null || !(obj instanceof UserPK))		   		
   		return false;		
 	  	else if (pkValues.get("ID").equals(((UserPK)obj).pkValues.get("ID"))) 
	
			return true;						
			else 				
		return false;
	}

  // this method must be provided for oprations on UniversumHome object such as 
	// create() and findBy methods except findByPrimaryKey() method where a public 
	// constructor must be used
	// arguments of the constructor are meaningless
  public static UserPK getInstance(){
 		return new UserPK(new Integer(0));
 	}
   
   
 	public UserPK(Integer id)   {
     pkValues.put(pkColumns[0], id);
     init();
   }
   

	
	
	 public UniversumPK insert(UniversumData beanAttributes, Connection con)throws SQLException{    
	 	  //make sure that data elements are valid
			validate(beanAttributes);
	
      PreparedStatement ps  = con.prepareStatement(insertQuery);      
     	for (int i = 0; i < columns.length; i++)
       ps.setObject(i+1, beanAttributes.get(columns[i]));     
      
      if (ps.executeUpdate() != 1) throw new SQLException();
    
      return new UserPK((Integer)beanAttributes.get("ID"));
	 }
   
   
	 public void delete(Connection con) throws SQLException{
    PreparedStatement ps  = con.prepareStatement(deleteQuery);
   	for (int i = 0; i < pkColumns.length; i++)
       ps.setObject(i+1, pkValues.get(pkColumns[i]));      

    if (ps.executeUpdate() != 1) throw new SQLException(); 
    


   }
   
   public void update(UniversumData beanAttributes, Connection con)throws SQLException{ 
   	//it is the bean responsibility to validate beanAttributes data 
   	// it is assumed here that data are valid and uts size is right
   	PreparedStatement ps  = con.prepareStatement(updateQuery);
   	int counter = 1;
   	String col = null;
   	for (int i = 0; i < columns.length; i++){
   		 col = columns[i];
   		 if (pkValues.containsKey(col)){
   		 		if(!pkValues.get(col).toString().equals(beanAttributes.get(col).toString()))
   		 			throw new SQLException("update of primary key value is not allowed " + columns[i]);
   		 }
   		 
       ps.setObject(counter++, beanAttributes.get(col));
   	}
       
   	
   	for (int i = 0; i < pkColumns.length; i++)
       ps.setObject(counter++, pkValues.get(pkColumns[i]));
    
    if (ps.executeUpdate() != 1) throw new SQLException();    

	 }

   
   public UniversumData select(Connection con) throws SQLException{    
   	HashMap map = new HashMap();

    PreparedStatement ps  = con.prepareStatement(selectQuery);
   	for (int i = 0; i < columns.length; i++)
       ps.setObject(i+1, pkValues.get(columns[i])); 
    ps.executeQuery();
    
    ResultSet rs = ps.getResultSet();
      
    if (rs.next()) 
    	 for (int i = 0; i < columns.length; i++)
       		map.put(columns[i],rs.getObject(i+1));            
    else 
       throw new SQLException ("record not found");
       
    if(rs.next())
    	 throw new SQLException ("only one record expected");
    	 
    return new UniversumData(map);
   }

   	
   
   public  boolean exists(Connection con)	throws SQLException{ 

   	PreparedStatement ps  = con.prepareStatement(selectQuery);
   	for (int i = 0; i < columns.length; i++)
       ps.setObject(i+1, pkValues.get(columns[i])); 
    ps.executeQuery();
    
    ResultSet rs = ps.getResultSet();
      
    if (!rs.next()) return false;     
    return true;
       
   }
   
  public boolean validate(UniversumData attributes)throws SQLException{ 
  	//test if attributes contains valid data elements
  	Iterator it = attributes.getMap().keySet().iterator();
		outer: while (it.hasNext()) {
			String aName = (String)it.next();
			for (int i = 0; i < columns.length; i++){
				if(aName.equals(columns[i]))
					continue outer;   //match is found, proceed to next data element

			}
			//should not reach this place if entries are valid	
			throw new SQLException(aName + " is invalid name for " + this.getClass().getName());
		
		}
		return true;																
  }

  /** 
	* Custom finder method for this primary key class.
	* @param   String     
	* @exception   SQLException 
	* @return Collection of primary key instances
	*/   
   
  public java.util.Collection findBySQLWhere(String where, Connection con) throws SQLException{
  	
    PreparedStatement ps = null;
    UserPK pk;
      ps = con.prepareStatement(findByWhereQuery + where);      
      ps.executeQuery();
      ResultSet rs = ps.getResultSet();
      Vector v = new Vector();

      while (rs.next()) {
        pk = new UserPK((Integer)rs.getObject(1));
        v.addElement(pk);
      }
      return v;
  }
  
  
  /** 
	* Custom finder method for this primary key class.
	* @param   String     
	* @exception   SQLException 
	* @return Collection of primary key instances
	*/
  
  public static java.util.Collection findByName(String qst, UniversumHome home) 
  	throws SQLException, FinderException, RemoteException{
    String where = " FIRST_NAME = '" + qst + "'";    
		return home.findBySQLWhere(where, UserPK.getInstance());
  }
  
}

